<?php
$userid = $_POST['userid'];
$token = $_POST['token'];
$gdkey = $_POST['gdkey'];
$type = $_POST['type'];
include_once("../../untils/conn.php");

if ($con) {
    mysqli_query($con, "set names utf8");

    // 根据$type的值确定groups的取值
    $groups = ($type == "haokeyun") ? "haokeyun" : "gantanhao";

    // 查询数据库中的记录
    $result = mysqli_query($con, "SELECT * FROM config_api WHERE groups='$groups'");
    $row = mysqli_fetch_assoc($result);
    $num_rows = mysqli_num_rows($result);

    if ($num_rows > 0) {
        // 数据库中已存在记录，执行更新操作
        $update_query = "UPDATE config_api SET userid='$userid', token='$token'";
        if ($type == "haokeyun") {
            $update_query .= ", gdkey='$gdkey'";
        }
        $update_query .= " WHERE groups='$groups'";
        $update_result = mysqli_query($con, $update_query);

        if ($update_result) {
            echo "<script>alert('更新成功'); history.back();</script>";
        } else {
            echo "<script>alert('更新失败');history.back();</script>";
        }
    } else {
        // 数据库中不存在记录，执行插入操作
        $insert_query = "INSERT INTO config_api (groups, userid, token";
        $insert_values = "VALUES ('$groups', '$userid', '$token'";
        if ($type == "haokeyun") {
            $insert_query .= ", gdkey";
            $insert_values .= ", '$gdkey'";
        }
        $insert_query .= ") " . $insert_values . ")";
        $insert_result = mysqli_query($con, $insert_query);

        if ($insert_result) {
            echo "<script>alert('添加成功'); history.back(); </script>";
        } else {
            echo "<script>alert('添加失败'); history.back(); </script>";
        }
    }
} else {
    echo "<script>alert('数据库连接失败');</script>";
}

$con->close();
?>
